﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace CMS.DI
{
    public static class DependencyInjectionConfig
    {
        public static AutofacServiceProvider Configure(this IServiceCollection services, IConfigurationRoot configuration)
        {
            var builder = new ContainerBuilder();
            builder.Populate(services);
            var iService = Assembly.Load("IService");
            var service = Assembly.Load("Service");
            var iRepository = Assembly.Load("IRepository");
            var repository = Assembly.Load("Repository");
            //根据名称约定（服务层的接口和实现均以Services结尾），实现服务接口和服务实现的依赖
            builder.RegisterAssemblyTypes(iService, service)
              .Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))
              .AsImplementedInterfaces().PropertiesAutowired();
            builder.RegisterAssemblyTypes(iRepository, repository)
              .Where(t => t.Name.EndsWith("Repository"))
              .AsImplementedInterfaces().PropertiesAutowired();

            //注册所有控制器
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
            .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();

            return new AutofacServiceProvider(builder.Build());
        }
    }
}
